package com.jule.miaozhuapc.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jule.miaozhuapc.domain.WawaPay;
import com.jule.miaozhuapc.domain.WawaRecharge;
import com.jule.miaozhuapc.service.PayService;
import com.jule.miaozhuapc.service.RechargeService;
import com.jule.miaozhuapc.util.Const;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.pingplusplus.model.Event;
import com.pingplusplus.model.PingppObject;
import com.pingplusplus.model.Webhooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Servlet implementation class PingWebHooks
 */
@WebServlet("/PingWebHooks")
public class PingWebHooks extends HttpServlet {
	private static final long serialVersionUID = 1L;


	@Autowired
	RechargeService rechargeService;
	@Autowired
	PayService payService;
	private Logger logger = Logger.getLogger(this.getClass());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public PingWebHooks() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
			request.setCharacterEncoding("UTF8");
	        //获取头部所有信息
	        Enumeration headerNames = request.getHeaderNames();
	        while (headerNames.hasMoreElements()) {
	            String key = (String) headerNames.nextElement();
	            String value = request.getHeader(key);
	            System.out.println(key+" "+value);
	        }
	        // 获得 http body 内容
	        BufferedReader reader = request.getReader();
	        StringBuffer buffer = new StringBuffer();
	        String string;
	        while ((string = reader.readLine()) != null) {
	            buffer.append(string);
	        }
	        reader.close();
	        // 解析异步通知数据
			logger.info(buffer.toString());
	        Event event = Webhooks.eventParse(buffer.toString());

	        // 开发者在此处加入对支付异步通知的处理代码
	        if ("charge.succeeded".equals(event.getType())) {
	            PingppObject obj = Webhooks.getObject(buffer.toString()); 
	            try {

					String order_no = new JSONObject(obj).getString("orderNo");

					//解决Autowired为null无法注入问题
					if (rechargeService == null || payService == null) {
						WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
					}

					WawaRecharge wawaRecharge = rechargeService.findByOrderNo(order_no);
					if (wawaRecharge != null) {
						wawaRecharge.setSucTime(new Date());
						wawaRecharge.setStatus(1);

						//addCoin
						WawaPay pay = new WawaPay();
						pay.setAddTime(new Date());
						pay.setCoin(wawaRecharge.getCoin());
						pay.setIsDelete(false);
						pay.setMoney(wawaRecharge.getMoney());
						pay.setRemark("充值");
						pay.setType(Const.WAWA_PAY_TYPE_MONEY);
						pay.setUserId(wawaRecharge.getUserId());
						pay.setRechargeId(wawaRecharge.getId());

						payService.addCoin(pay);

						// 给 WX 200 状态 success
						response.setStatus(200);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					response.setStatus(500);
				}
	        } else if ("refund.succeeded".equals(event.getType())) {
	            // 开发者在此处加入对退款异步通知的处理代码

	            response.setStatus(200);
	        } else {
	            response.setStatus(500);
	        }
	    }
}
